<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <!-- 工具栏 -->
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
      />
      <!-- 编辑器 -->
      <Editor
        style="height: 400px; overflow-y: hidden"
        :defaultConfig="editorConfig"
        v-model="html"
        @onChange="onChange"
        @onCreated="onCreated"
      />
    </div>
  </div>
</template>
 
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import productApi from "@/api/product";
import { ElMessage } from "element-plus";

export default {
  name: "editorVue",
  components: { Editor, Toolbar },
  props: {
    content: {
      type: String,
      default: '',
    },
    readOnlys: { // 只读
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {
        /* 显示哪些菜单，如何排序、分组 */ 
        toolbarKeys: [
          'headerSelect', 
          // '|', 
          'bold', 
          'underline', 
          'italic', 
          'color', 
          'bgColor', 
          // '|', 
          'indent',  // 增加缩进
          'delIndent',  // 减少缩进
          'justifyLeft',  // 左对齐
          'justifyRight',  // 右对齐
          'justifyCenter',  // 居中
          'justifyJustify',  // 两端对齐
          // '|', 
          'fontSize', 
          'fontFamily', 
          'lineHeight', 
          // '|', 
          'bulletedList', 
          'numberedList', 
          'todo', 
          'insertLink', 
          'insertTable', 
          // '|', 
          'codeBlock', 
          'divider', 
          'uploadImage', 
          'undo', 
          'redo', 
        ], 
        // excludeKeys: [ ], /* 隐藏哪些菜单 */ 
      },
      editorConfig: {
        placeholder: "请输入内容",
        MENU_CONF: {
          uploadImage: {
            server: '', // 不需要设置 server，因为我们使用 customUpload
            fieldName: 'file',
            customUpload: this.customUploadImage,
            maxFileSize: 5 * 1024 * 1024,
            maxNumberOfFiles: 10,
            allowedFileTypes: ['image/*'],
            onError: function (file, err, res) {
              console.error('上传错误:', err);
              ElMessage.error(`图片上传失败: ${err.message || '未知错误'}`);
            },
            onSuccess: function(file, res) {
              console.log('上传成功:', res);
            }
          },
        },
      },
    };
  },
  watch: {
    readOnlys: {
      handler(newV) {
        if(newV) {
          this.editor.disable()  // 只读模式
        }
      }
    },
  },
  methods: {
    async customUploadImage(file, insertFn) {
      try {
        console.log('开始上传图片:', file);
        const formData = new FormData();
        formData.append('file', file);

        const res = await productApi.uploadImg(formData);
        console.log('上传响应:', res);
        
        if (res.data) {
          // 确保返回的是完整的URL
          const imageUrl = res.data;
          console.log('插入图片URL:', imageUrl);
          insertFn(imageUrl);
          ElMessage.success('图片上传成功');
        } else {
          console.error('上传响应中没有data:', res);
          ElMessage.error('图片上传失败: 服务器响应异常');
        }
      } catch (error) {
        console.error('图片上传错误:', error);
        ElMessage.error('图片上传失败: ' + (error.message || '未知错误'));
      }
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
    },
    onChange(editor) {
      this.$emit('changeData', this.html)
    },
  },
  created() {

    this.html = this.content;
    console.log(this.content);
    console.log("++++++++++");
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁 editor
  },
};
</script>
 
<style src="@wangeditor/editor/dist/css/style.css"></style>
